<template>
  <div id="app">
    <el-container>
      <el-main id="pageMain">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="网点/机构名称:">
            <el-input v-model="search.searchObj.siteName" @keydown.13.native="queryListMethod"
                      placeholder="请输入网点/机构名称"
                      :value="null" clearable></el-input>
          </el-form-item>

          <el-form-item label="目的网点:" prop="destinationCity">
            <el-cascader v-model="addrSelect" placeholder="可搜索" :options="options" filterable clearable
                         @change="handleChange">
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="queryListMethod">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="cleanSearch">清空</el-button>
          </el-form-item>
          <el-form-item>
            <!--            <el-button type="success" icon="el-icon-" >刷新</el-button>-->
            <el-button type="success" icon="el-icon-refresh" @click="this.flushPage"></el-button>
          </el-form-item>
        </el-form>
        <el-table :data="dataList" align="center" border style="width: 100%" height="390px">
          <el-table-column align="center" label="编号" type="index" width="85px">
          </el-table-column>
          <el-table-column align="center" label="机构名称" prop="name"></el-table-column>
          <el-table-column align="center" label="所在区" prop="address"></el-table-column>
          <el-table-column align="center" label="联系电话" prop="contractNumber"></el-table-column>
          <el-table-column align="center" label="每日调度时间" prop="scheduleConf">
            <template slot-scope="scope">{{ scope.row.scheduleConf | convertCronToReadable }}</template>
          </el-table-column>
          <el-table-column align="center" label="调度策略" prop="executorParam">
            <template v-slot="data">
              <span v-for="(item) in executorParamOption" :key="item.value" v-if="item.value == data.row.executorParam">{{
                  item.name
                }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="运行状态" prop="triggerStatus">
            <template v-slot="data">
              <span v-if="data.row.triggerStatus == null || data.row.triggerStatus == ''" style="color: red">
                未设置任务
              </span>
              <span v-if="data.row.triggerStatus == 0">
                <el-switch readonly :value="false" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </span>

              <span v-if="data.row.triggerStatus == 1">
                <el-switch readonly :value="true" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </span>
            </template>
          </el-table-column>
          <!--          <el-table-column align="center" label="调度备注" prop="jobDesc"></el-table-column>-->
          <el-table-column align="center" label="查看日志" prop="id">
            <template v-slot="data">
              <el-button @click="queryJobLog(data.row)" type="primary" icon="el-icon-document-copy"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 30px"></div>
        <el-footer>
          <div class="block">
            <el-pagination :current-page="search.currentPage" :page-size="search.pageSize" :page-sizes="[5, 10, 15, 20]"
                           :total="search.total" layout="total, sizes, prev, pager, next, jumper"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange">
            </el-pagination>
          </div>
        </el-footer>
      </el-main>
    </el-container>

    <el-dialog :visible.sync="centerDialogVisible" center top="10px" width="70%" >
      <el-tabs type="border-card">
        <el-tab-pane>
          <span slot="label"><i class="el-icon-date"></i> 日志记录</span>
          <el-main id="pageMain">

            <el-table :data="dataJobLogList" align="center" border style="width: 100%" height="390px">
              <el-table-column align="center" label="编号" type="index" width="85px">
              </el-table-column>
              <el-table-column align="center" label="调度策略" prop="executorParam">
                <template v-slot="data">
              <span v-for="(item) in executorParamOption" :key="item.value" v-if="item.value == data.row.executorParam">{{
                  item.name
                }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="调度结果" prop="triggerCode">
                <template v-slot="data">
                  <span v-if="data.row.triggerCode==200" style="color: green">成功</span>
                  <span v-else style="color: red">失败</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="执行时间" prop="handleTime"></el-table-column>
            </el-table>
            <div style="height: 30px"></div>
            <el-footer>
              <div class="block">
                <el-pagination :current-page="searchJobLog.currentPage" :page-size="searchJobLog.pageSize"
                               :page-sizes="[5, 10, 15, 20]"
                               :total="searchJobLog.total" layout="total, sizes, prev, pager, next, jumper"
                               @size-change="handleSizeChange"
                               @current-change="handleCurrentChange">
                </el-pagination>
              </div>
            </el-footer>
          </el-main>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false" type="primary">关 闭</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  CodeToText,
  TextToCode
} from 'element-china-area-data'
import CronParser from "cron-parser";

export default {
  filters: {
    convertCronToReadable(cronExpression) {
      if (!cronExpression) {
        return ''
      }
      const CronParser = require('cron-parser');
      try {
        const interval = CronParser.parseExpression(cronExpression).next();
        const nextExecutionTime = interval.toDate().toLocaleString();
        return nextExecutionTime.substring(nextExecutionTime.indexOf(' '), nextExecutionTime.length - 3);
        // return nextExecutionTime;
      } catch (error) {
        console.error('无法解析cron表达式:', error);
        return null;
      }
    },
  },
  name: "job-log",
  data() {
    return {
      options: regionData,
      addrSelect: [],
      executorParamOption:
        [
          {'name': '距离最少', 'value': 'distance'},
          {'name': '成本最少', 'value': 'cost'},
          {'name': '中转最少', 'value': 'transfer'},
          {'name': '时间最少', 'value': 'estimatedTime'},
        ],
      search: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
        searchObj: {
          siteName: "",
          districtId: "",
          jobStatus: '1',
        },
      },
      searchJobLog: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
        jobId: '',
      },
      centerDialogVisible: false,
      dataList: [],
      dataJobLogList: [],
      currentObjTemp: {},
      jobId:'',
    }
  },
  watch: {
    'search.currentPage': function () {
      this.queryListMethod()
    },
    'search.pageSize': function () {
      this.queryListMethod()
    },
    'searchJobLog.currentPage': function () {
      this.queryJobLog()
    },
    'searchJobLog.pageSize': function () {
      this.queryJobLog()
    },
  },
  methods: {
    async queryJobLog(row) {
      this.searchJobLog.jobId=row.jobId

      let newVar = await axios.post('/api/dispatch-service/xxl-job-log/queryJobLogByJobId', this.searchJobLog);
      console.log(newVar.data.list)
      this.dataJobLogList = newVar.data.list
      this.searchJobLog.total = newVar.data.total
      this.centerDialogVisible = true
      if (this.searchJobLog.total) {
        this.$message({
          type: 'success',
          message: '查询成功！',
          center: true,
        });
      }
    },
    async flushPage() {
      await axios.post("/api/dispatch-service/SmartDispatch/flushPage")
      await this.queryListMethod()
    },

    convertCronToReadable(cronExpression) {
      if (!cronExpression) {
        return ''
      }
      const CronParser = require('cron-parser');
      try {
        const interval = CronParser.parseExpression(cronExpression).next();
        const nextExecutionTime = interval.toDate().toLocaleString();
        return nextExecutionTime.substring(nextExecutionTime.indexOf(' '), nextExecutionTime.length - 3);
        // return nextExecutionTime;
      } catch (error) {
        console.error('无法解析cron表达式:', error);
        return null;
      }
    },

    handleChange(value) {
      this.search.searchObj.districtId = value[2];
    },
    cleanSearch() {
      this.addrSelect = [],
        Object.keys(this.search.searchObj).forEach(key => (this.search.searchObj[key] = ''));
    },

    handleSizeChange(val) {
      this.search.pageSize = val
    },
    handleCurrentChange(val) {
      this.search.currentPage = val
    },
    handleSizeChange1(val) {
      this.searchJobLog.pageSize = val
    },
    handleCurrentChange1(val) {
      this.searchJobLog.currentPage = val
    },

    async queryListMethod() {
      let newVar = await axios.post('/api/dispatch-service/pd-order-classify/queryCoreOrgList', this.search);
      console.log(newVar.data.list)
      this.dataList = newVar.data.list
      this.search.total = newVar.data.total
      if (this.search.total) {
        this.$message({
          type: 'success',
          message: '查询成功！',
          center: true,
        });
      }
    },

  },
  created() {
    this.queryListMethod()
  }
}
</script>

<style scoped>
#pageMain {
  height: 570px;
}

.el-footer {
  text-align: center;
}

* {
  letter-spacing: 3px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
